<template>
	<view>
		<view class="page__content">
			<up-navbar :fixed="false" title="新建实验室任务" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</up-navbar>

			<view class="page__content__main">
				<up-form labelPosition="left" :model="formData" :rules="rules" ref="baseFormRef" labelWidth="120">
					<up-form-item label="产品名称" prop="ProductName" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('产品','radio')">
							<up-input v-model="formData.ProductName" readonly placeholder="请选择"
								border="none"></up-input>
						</view>

						<template #right>
							<up-icon name="arrow-right" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>
					<view class="f-dc" v-if="formData.ProductID"
						style="background-color: #f4f5fa;font-size: 12px;padding: 10rpx;color: #6f6f6f;font-weight: 600;border-radius: 5px;">
						<text>产品编号：{{formData.ProductCode}}</text>
						<text style="margin-top: 10rpx;">产品规格：{{formData.ProductSpec}}</text>
					</view>

					<up-form-item label="检测方案" prop="BillNO" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView">
							<up-input v-model="formData.BillNO" readonly placeholder="请选择" border="none"></up-input>
						</view>
					</up-form-item>

					<up-form-item label="接收质量限" prop="AQL" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView">
							<up-input v-model="formData.AQL" readonly placeholder="请选择" border="none"></up-input>
						</view>
					</up-form-item>

					<up-form-item label="样本数量" prop="BJNum" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView">
							<up-input v-model="formData.BJNum" type="number" :readonly="uni.$utils.isEmpty(formData.LabTestPlanID)"
								:placeholder="uni.$utils.isEmpty(formData.LabTestPlanID) ? '请确认检验方案' : '请输入样本数量'"
								border="none" @blur="getCJNumByBJNum"></up-input>
						</view>

						<template #right>
							<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>
					<view class="f-dc" v-if="formData.CJNum"
						style="background-color: #f4f5fa;font-size: 12px;padding: 10rpx;color: #6f6f6f;font-weight: 600;border-radius: 5px;">
						<text>抽样数量：{{formData.CJNum}}</text>
						<text style="margin-top: 10rpx;">拒收数：{{formData.RejectionNum}}</text>
					</view>

					<up-form-item label="负责人" prop="CuratorName" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('负责人','radio')">
							<up-input v-model="formData.CuratorName" readonly placeholder="请选择"
								border="none"></up-input>
						</view>

						<template #right>
							<up-icon name="arrow-right" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item label="预计结束时间" :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('预计结束时间','time')">
							<up-input v-model="formData.TestEndTime" readonly placeholder="请选择"
								border="none"></up-input>
						</view>

						<template #right>
							<up-icon name="calendar-fill" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>

				</up-form>
			</view>

			<view class="page__content__bottom">
				<button class="CommonBtnSize content_bottom_primary_Btn" style="margin-left: 10px;"
					@click="insetRow">提交</button>
			</view>

		</view>

	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	let formData = reactive<any>({// 产品
		ProductCode: null,
		ProductName: null,
		ProductSpec: null,
		ProductInfo: null,
		ProductID: null,

		// 检测方案
		LabTestPlanID: null,
		BillNO: null,
		SamplingSchemeID: null,
		// 接收质量限
		AQL: null,
		// 送检数量
		BJNum: null,
		// 拒收数
		RejectionNum: null,
		// 负责人
		Curator: null,
		CuratorName: null,
		// 截止日期
		TestEndTime: null,
	});

	interface UFormsInstance {
		validate : (callback ?: (isValid : boolean) => void) => Promise<boolean>
		resetFields : () => void;
		setRules : any;
	}
	const baseFormRef = ref<UFormsInstance | any>(null);

	let rules = {
		'ProductName': {
			type: 'string',
			required: true,
			message: '请选择产品',
			trigger: ['change']
		},
		'BillNO': {
			type: 'string',
			required: true,
			message: '未查询到检测方案',
			trigger: ['change']
		},
		'AQL': {
			type: 'string',
			required: true,
			message: '未查询到接收质量限',
			trigger: ['change']
		},
		'BJNum': {
			type: 'number',
			required: true,
			message: '请输入样本数量',
			trigger: ['blur']
		},
		'CuratorName': {
			type: 'string',
			required: true,
			message: '请选择负责人',
			trigger: ['change']
		}
	};

	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'createTicet_choice_' + routes.length
	});

	// 时间选择起选中时间数据
	let defaultData = reactive<any>({
		choiceTime: null
	});
	// 时间选择器
	let showDateTimePicker = ref(false)

	const openBaseScreen = (str : string, type : string) => {
		switch (type) {
			case 'radio':
			case 'check':
				switch (str) {
					case "产品":
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_Material', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							multiple: false, // 是否开启多选
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "ProductInfo", // 显示值
									hiddenValue: "ProductID", // 隐藏值
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								choiceData: formData.ProductID, // 选中数据
								choiceDataKey: "ProductID", // 选中数据的key
								isTree: false, // 是否开启树型下拉
							},
							param: { // 传递参数
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						});

						break;
					case "负责人":
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_Employee', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							multiple: false, // 是否开启多选
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "EmplName", // 显示值
									hiddenValue: "EmplID", // 隐藏值
									pageIndex: "Pageindex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'EmplCode', //搜索关键词，应包含在param中
								subText: [{
									label: "编号", // label文本
									labelKey: "EmplCode", // 显示label文本后文字的key
								}],
								choiceData: formData.EmplID, // 选中数据
								choiceDataKey: "EmplID", // 选中数据的key
							},
							param: { // 传递参数
								EmplCode: '',
								Pageindex: 1,
								PageSize: 30
							}
						});

						break;
					default:
						break;
				};

				break;

			case 'time':
				switch (str) {
					case "预计结束时间":
						let nowTime = new Date();
						if (!uni.$utils.isEmpty(formData.TestEndTime)) {
							nowTime = new Date(formData.TestEndTime);
						};
						defaultData.choiceTime = +nowTime;
						showDateTimePicker.value = true;
						break;
					default:
						break;
				}

				break;
			default:
				break;
		}
	}

	// 样本数量失焦,根据送检数量获取抽样数量
	const getCJNumByBJNum = (val : any) => {
		if (uni.$utils.isEmpty(val)) {
			let obj = {
				BJNum: null,
				CJNum: null,
			};
			Object.assign(formData, obj);
			return;
		};
		baseFormRef.value.validateField('BJNum');

		request({
			config: {},
			url: 'Qu_LabTestGetCjNum',
			method: 'POST',
			data: {
				BJNum: val,
				SamplingSchemeID: formData.SamplingSchemeID
			},
			success: async (ret : any) => {
				if (ret.status == 200) {

					formData.CJNum = ret.data.ds[0]['CJNum'];
					formData.RejectionNum = ret.data.ds[0]['RejectionNum'];
				}
			}

		})


	}

	const UserInfo = computed(() => {
		return userStore.UserInfo;
	})

	const insetRow = () => {
		uni.$utils.showLoading("正在校验...");

		baseFormRef.value.validate().then(res => {
			uni.$utils.showLoading("校验成功，准备提交");

			let param = {
				ProductID: formData.ProductID,
				Curator: formData.Curator,
				SamplingSchemeID: formData.SamplingSchemeID,
				BJNum: formData.BJNum,
				UserName: UserInfo.value.UserName,
				LabTestPlanID: formData.LabTestPlanID,
				TestEndTime: formData.TestEndTime
			};

			request({
				config: {},
				url: 'Qu_LabTestCreateBillNO',
				method: 'POST',
				data: param,
				success: async (ret : any) => {
					if (ret.status == 200) {
						if (ret.data.ds[0]['status'] == 200) {
							// 画一个弹层，用于提示成功，并确认退出或继续编辑
							uni.$utils.hideLoading();
							uni.showToast({
								title: "提交成功！"
							});
							uni.$emit("refresh_labreport_list");
							uni.navigateBack();
						}
					}
				}
			})

		}).catch((errors : any) => {
			console.log(errors);
			uni.$utils.hideLoading();
			uni.$utils.msg("请完善表单信息")
		})

	};

	// 根据产品信息获取检测方案
	const getLabReportPlanByProduct = () => {
		uni.$utils.clearFormData(formData, ["ProductID", "ProductName", "ProductCode", "ProductInfo",
			"ProductSpec", "Curator", "CuratorName", "TestEndTime"
		]);
		if (uni.$utils.isEmpty(formData.ProductID)) {
			return uni.$utils.layer.alert("当前物料信息加载异常，请重新选择物料！")
		};

		request({
			config: {},
			url: 'Qu_LabTestSelectPlanByProduct',
			method: 'POST',
			data: {
				ProductID: formData.ProductID
			},
			success: async (ret : any) => {
				console.log(ret);
				if (ret.status == 200) {
					let data = {
						LabTestPlanID: null,
						BillNO: null,
						SamplingSchemeID: null,
						AQL: null,
					};

					if (ret.data.ds.length) {
						Object.assign(data, ret.data.ds[0]);
					};
					Object.assign(formData, data);

					baseFormRef.value.validateField('BillNO');
					baseFormRef.value.validateField('SamplingSchemeID');
					baseFormRef.value.validateField('AQL');
				}
			}
		})

	}

	onLoad(() => {
		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			switch (ret.titleName) {
				case "产品":
					Object.assign(formData, ret.data);

					baseFormRef.value.validateField('ProductName');
					// 根据产品信息获取检测方案
					getLabReportPlanByProduct();
					break;
				case "负责人":
					let data = {
						Curator: ret.data["EmplID"],
						CuratorName: ret.data["EmplCode"] + "_" + ret.data["EmplName"],
					}
					Object.assign(formData, data);
					baseFormRef.value.validateField('CuratorName');
					break;
				default:
					break;
			}
		})
	});

	onUnload(() => {
		uni.$off(baseScreenListenName.value);
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;
	}
</style>